package cn.itsource.itsource.controller;

import cn.itsource.itsource.config.WechartProperties;
import cn.itsource.itsource.dto.BinderDto;
import cn.itsource.itsource.service.IWechartService;
import cn.itsource.itsource.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

@Controller//特点注意：与微信交互，因为要返回页面，需要重定向，这里不能写  @RestController。理由：因为这个注解返回 的都是sjon，而不能返回页面

@RequestMapping("/wechart")

public class WechartController {


    @Autowired

    private WechartProperties wechartProperties;

    @Autowired
    private IWechartService wechartService;

    //申请微信登录

    @GetMapping("/apply")

    public String apply(){

        //https://open.weixin.qq.com/connect/qrconnect?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_login&state=%s#wechat_redirect

        //生成一个唯一标识作为state

        String state = UUID.randomUUID().toString().replace("-","");

        //生成完整的授权码URL

        String authorizationCodeUrl = String.format(wechartProperties.getAuthorizationCodeUrl(), wechartProperties.getAppId(), wechartProperties.getRedirectUri(), state);
        //在这里进行重定向
        return "redirect:"+authorizationCodeUrl;


    }

    @GetMapping("/callback")
    //@ResponseBody //返回json字符串
    public String callback(String code, String state) {
            AjaxResult result=wechartService.callback(code,state);
            if(result.getSuccess()==true){// 跳转到首页
                return "redirect:http://localhost:8082/index.html";

            }else {
                //跳绑定页面
                return "redirect:http://localhost:8082/binder.html?openid="+result.getData().toString();

            }

    }

    @PostMapping("/binder")
    @ResponseBody
    public AjaxResult binder(@RequestBody BinderDto dto){

        return wechartService.binder(dto);
    }

}